package com.jackeysun.app_common

import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.jackeysun.app_common.databinding.ActivityMain3Binding
import com.jackeysun.common.text.*
import com.jackeysun.common.text.StringExt.Span
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

import android.annotation.SuppressLint
import android.content.Context

import android.graphics.BitmapFactory
import android.text.*

import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.widget.TextView
import com.jackeysun.common.view.*
import com.jackeysun.util.scale
import android.view.LayoutInflater
import android.widget.TextView.BufferType

import com.jackeysun.common.text.MarkerViewSpan


import com.jackeysun.util.toObject
import java.util.regex.Pattern


class MainActivity3 : AppCompatActivity(), CoroutineScope by MainScope() {
    lateinit var main3Binding: ActivityMain3Binding

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        main3Binding = ActivityMain3Binding.inflate(layoutInflater)
        setContentView(main3Binding.root)

        main3Binding.tv.setOnClickListener {
            startActivity(Intent(this@MainActivity3, MainActivity4::class.java))
        }



        main3Binding.btn.setOnClickListener {

            if (main3Binding.tv3.isVisible()) {
                main3Binding.tv3.gone()
            } else {
                main3Binding.tv3.visible()
            }

        }


//        this.launch {
//            val h = main3Binding.tv3.w()
//            val h2 = main3Binding.tv3.getWidth2()
//            Log.d("MainActivity3", "onCreate: $h  $h2")
//        }

//        SpannableStringBuilder()
//            .addSection("我已阅读并同意")
//            .addStyleSection(
//                "《考试蚁用户注销协议》",
//                ForegroundColorSpan(Color.WHITE),
//                BackgroundColorSpan(Color.BLUE),
//                AbsoluteSizeSpan(24.sp2px()),
//                StyleSpan(Typeface.BOLD)
//            ).into(main3Binding.tv)

//        var isOpen = false


        val markerView: View =
            LayoutInflater.from(this).inflate(R.layout.item_marker_fore_title, null)
        val tvDegreeMarker: TextView = markerView.findViewById(R.id.item_degree_marker)
        val tv: TextView = markerView.findViewById(R.id.tv)
        val sp = SpannableStringBuilder("  未作答  ")
        sp.setSpan(UnderlineSpan(), 0, sp.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        tv.text = sp

        markerView.setOnClickListener {
            val sp = SpannableStringBuilder("  mark  ")
            sp.setSpan(UnderlineSpan(), 0, sp.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            tv.text = sp
        }
//        val builder = SpannableStringBuilder()
//        val REPLACE_TEXT = " "
//        builder.append(REPLACE_TEXT)
//        builder.setSpan(
//            MarkerViewSpan(markerView),
//            0,
//            REPLACE_TEXT.length,
//            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
//        )
//        val oriText: String = main3Binding.tv2.getText().toString()
//        builder.append(oriText)
//        main3Binding.tv2.text = builder


//        val topSpan = IconTextSpan(applicationContext, R.color.black, "26")
//        val b = BitmapFactory.decodeResource(resources, R.drawable.ic_translate_en)
//        val imgSpan = CenterImageSpan(this, b scale 0.4f)
//        Span.addStyleSection(
//            DataSource.en,
//            Color.parseColor("#FF13141A"),
//            14
//        ).addStyleSection(
//            " ",
//            MarkerViewSpan(markerView),
//            Click{
//                Log.d("TAG", "onCreate: mark")
//            }
//        ).addStyleSection(
//            "22222222",
//            imgSpan,
//            Click {
////                open(false)
//                Log.d("TAG", "onCreate: img")
//            }
//        ).addStyleSection(
//            "${DataSource.cn}",
//            Color.parseColor("#FF858593"),
//            14
//        ).into(main3Binding.tv2)

//        val showString =
//            SpannableString("1234533333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333336")
////        val imageSpan = imgSpan
////        val imageSpan2 = JImageSpan(this, R.mipmap.sym_def_app_icon)
////        val imageSpan21 = JImageSpan(this, R.drawable.sym_def_app_icon)
//        showString.setSpan(imgSpan, 2, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
//        showString.setSpan(imgSpan, 27, 30, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
//        showString.setSpan(imgSpan, 77, 78, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
//        main3Binding.tv2.setText(showString)


//        open(false)

//        Span.addStyleSection(
//            DataSource.en,
//            Color.parseColor("#FF13141A"),
//            14
//        ).addStyleSection(
//            5,
//            Click{
//
//            }
//        ).into(main3Binding.tv2)


//        main3Binding.tv2.setOnTouchListener(OnTouchListener { v, event ->
//            val text = (v as TextView).text
//            val sText = Spannable.Factory.getInstance().newSpannable(text)
//            val widget = v as TextView
//            val action = event.action
//            if (action == MotionEvent.ACTION_UP ||
//                action == MotionEvent.ACTION_DOWN
//            ) {
//                var x = event.x.toInt()
//                var y = event.y.toInt()
//                x -= widget.totalPaddingLeft
//                y -= widget.totalPaddingTop
//                x += widget.scrollX
//                y += widget.scrollY
//                val layout: Layout = widget.layout
//                val line: Int = layout.getLineForVertical(y)
//                val off: Int = layout.getOffsetForHorizontal(line, x.toFloat())
//                val imageSpans: Array<ClickableSpan> =
//                    sText.getSpans(off, off, ClickableSpan::class.java)
//                if (imageSpans.isNotEmpty()) {
//                    if (action == MotionEvent.ACTION_UP ) {
//                        val imageSpan = imageSpans[0]
//                        imageSpan.onClick(widget)
//                    }
//                    return@OnTouchListener true
//                }
//            }
//            false
//        })


//        val b = BitmapFactory.decodeResource(resources, R.mipmap.sym_def_app_icon)
//        val imgSpan = ImageSpan(this, b scale 0.4f, DynamicDrawableSpan.ALIGN_BOTTOM)
//            Span.insertStyleSection(
//                1,
//                imgSpan,
//                Click{
////                    open(false)
//                }
//            ).into(main3Binding.tv2)

//        main3Binding.tv2.movementMethod = LinkMovementMethod.getInstance();
        val mainTitleList = DataSource.datalist.toObject<List<TitleEnCn>>()
        mainTitleList.toTranslate(this, main3Binding.tv2)

//        main3Binding.tv2
//            .animate()
//            .alpha(1f)
//            .setDuration(500)
//            .start()

//        ValueAnimator.ofInt(12, 18).apply {
//            addUpdateListener {
//                Span.addSection("我已阅读并同意")
//                    .addStyleSection(
//                        "《*********协议》",
////                        textColor = Color.WHITE,
//                        textSize = it.animatedValue as Int,
////                        backgroundColor = Color.BLUE,
////                        textStyle = Typeface.BOLD
//                    ).into(main3Binding.tv)
//            }

//            duration = 500
//            repeatCount = ValueAnimator.INFINITE
//            repeatMode = ValueAnimator.REVERSE
//            start()
//        }

    }

//    private fun open(isOpen: Boolean = false) {
//        val b = BitmapFactory.decodeResource(resources, R.drawable.ic_translate_en)
//        val imgSpan = CenterImageSpan(this, b scale 0.4f)
//        if (isOpen) {
//            Span.addStyleSection(
//                DataSource.en,
//                Color.parseColor("#FF13141A"),
//                14
//            ).addStyleSection(
//                "22222222",
//                imgSpan,
//                Click {
//                    open(false)
//                }
//            ).addStyleSection(
//                "\n${DataSource.cn}",
//                Color.parseColor("#FF858593"),
//                14
//            ).into(main3Binding.tv2)
//        } else {
//            Span.addStyleSection(
//                DataSource.en,
//                Color.parseColor("#FF13141A"),
//                14
//            ).addStyleSection(
//                "22222222",
//                imgSpan,
//                Click {
//                    open(true)
//                }
//            ).into(main3Binding.tv2)
//        }
//    }

}

class Click(val click: (widget: View) -> Unit) : ClickableSpan() {

    override fun onClick(widget: View) {
        click(widget)
    }

}

fun List<TitleEnCn>.toTranslate(context: Context, tv: SelectableTextView) {
    val that = this
    var indexStart = 26
    that.forEach {
        val b = BitmapFactory.decodeResource(
            context.resources,
            if (it.isOpen) R.mipmap.ic_translate_en else R.mipmap.ic_translate_cn
        )
        val imgSpan = CenterImageSpan(context, b scale 0.8f)
        val pattern = "【([2-3]{1}[0-9]{1})】"
        val toSpan = SpannableStringBuilder(it.en)
        val words = getWordInfo(toSpan, pattern)
        words?.forEachIndexed { index, word ->
            val markerView: View =
                LayoutInflater.from(context).inflate(R.layout.item_marker_fore_title, null)
            val tvDegreeMarker: TextView = markerView.findViewById(R.id.item_degree_marker)
            val content: TextView = markerView.findViewById(R.id.tv)
            val sp = SpannableStringBuilder("  未作答  ")
            tvDegreeMarker.text = "$indexStart"
            indexStart++
            sp.setSpan(UnderlineSpan(), 0, sp.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            content.text = sp
            toSpan.setSpan(
                MarkerViewSpan(markerView),
                word.start,
                word.end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            toSpan.setSpan(Click { view ->
                Log.d("TAG", "toTranslate: mark ${word.start}, ${word.end}")
                val sp1 = SpannableStringBuilder("ssssssssssss")
                sp1.setSpan(UnderlineSpan(), 0, sp1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                content.text = sp1
                toSpan.setSpan(
                    MarkerViewSpan(markerView),
                    word.start,
                    word.end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                view.invalidate()
                Selection.removeSelection(toSpan)
                Log.d("TAG", "toTranslate: $toSpan")
            }, word.start, word.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        }

        Span.addStyleSection(
            toSpan,
            Color.parseColor("#FF13141A"),
            15,
            Color.TRANSPARENT
        )
        Span.addStyleSection(
            " \n",
            imgSpan,
            Click { view ->
                Log.d("TAG", "toTranslate: img")
                it.isOpen = !it.isOpen
                that.toTranslate(context, tv)
            }
        )
        if (it.isOpen) {
            Span.addStyleSection(
                "\n${it.cn}\n\n",
                Color.parseColor("#FF858593"),
                15,
                backgroundColor = Color.TRANSPARENT
            )
        }
    }
    Span.into(tv)
    tv.movementMethod = LinkMovementMethod.getInstance()
}

/**
 * 获取字符串中的数字
 */
//fun String.getDigital(): String {
//    val digital = StringBuffer()
//    val matcher = Pattern.compile("\\d").matcher(this)
//    while (matcher.find()) {
//        digital.append(matcher.group())
//    }
//    return digital.toString()
//}

//fun TextView.getEditable(): Editable? {
//    val text: CharSequence = this.text ?: return null
//    // This can only happen during construction.
//    if (text is Editable) {
//        return this.text as Editable
//    }
//    this.setText(text, BufferType.EDITABLE)
//    return this.text as Editable
//}